import {
    RouteComponentProps
} from 'react-router-dom';
import * as Immutable from 'immutable';
import * as fetch from 'isomorphic-fetch';

/**
 * 默认的跳转地址
 */
export const DEFAULT_REDIRECT_PATH = '/__al';

export const DEFAULT_TOKEN_KEY = '__tm_auth_token__';

export const DEFAULT_USE_INFO_KEY = '__tm_auth_user__';

export const LOGIN_REDIRECT_KEY = '__tm_login_redirect__';

let tokenCache: Immutable.Map<string, any> | undefined;
let userCache: Immutable.Map<string, any> | undefined;

const home = () => {
    const { protocol, host } = window.location;

    return protocol + '//' + host + '/';
};

const logonCb = () => {
    return `${home()}#/__acb`;
};

/**
 * 登录
 */
export const login = () => {
    window.location.href =
        // tslint:disable-next-line:max-line-length
        `${__AUTH_URL}?response_type=code&scope=&state=&client_id=${__APP_ID}&redirect_uri=${encodeURIComponent(logonCb())}`;
};

/**
 * 登出
 */
export const logout = () => {
    clearUser();
    clearToken();

    if (window.__ELE__) {
        window.logout();
    } else {
        window.location.href = `${__LOGOUT_URL}?redirect_uri=${encodeURIComponent(home())}`;
    }
};

/**
 * 提供的默认身份验证
 * @param props
 */
export const defaultAuthVerify = (props: RouteComponentProps<any>): boolean => true;
    // window.__ELE__ ? (null !== getUser()) : (null !== getToken() && null !== getUser());

/**
 * 获取缓存中已登录的token
 */
export const getToken = () => {
    return tokenCache || loadToken();
};

/**
 * 获取缓存中已登录的用户信息
 */
export const getUser = () => {
    return userCache || loadUser();
};

/**
 * 使用 authCode 交换 access token
 * @param code
 */
export const exchangeToken = (code: string): Promise<any> => {
    return new Promise((resolve, reject) => {
        fetch(__TOKEN_URL, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            // tslint:disable-next-line:max-line-length
            body: `grant_type=authorization_code&client_id=${__APP_ID}&client_secret=}&code=${code}&redirect_uri=${logonCb()}`
        })
            .then((response) => {
                return response.json();
            }).then((ret) => {
                if (0 !== ret.code) {
                    reject(ret.data);

                    return;
                }
                resolve(ret.data);
            }).catch((error) => {
                reject({
                    name: 'Exchange access token failed',
                    message: `交换授权票据失败：${error.message}`,
                    code: 0
                });
            });
    });
};

export const getUserInfo = (token: string): Promise<any> => {
    return new Promise((resolve, reject) => {
        fetch(`${__USER_INFO_URL}/${token}`)
            .then((response) => {
                return response.json();
            }).then((ret) => {
                if (ret.result) {
                    resolve(ret.userData);
                } else {
                    reject(ret.userData);
                }
            }).catch((error) => {
                reject({
                    name: 'Get user info failed',
                    message: `获取用户信息失败 ${error.message}`,
                    code: 0
                });
            });
    });
};

/**
 * 检查 accessToken 是否已过期
 * @param createOn
 * @param lifetime
 */
export const checkTokenExpired = (createOn: number, lifetime: number): boolean => {
    // 检查是否过期
    return (Date.now() - createOn > (lifetime + 10) * 1000);
};

/**
 * 获取授权请求头
 */
export const getAuthFetchHeader = (): { header: string, value: string } => {
    if (window.__ELE__) {
        const eleParams = window.getElectronRequestHeaderParams();

        return {
            header: eleParams.authHeader,
            value: `${eleParams.authPrefix} ${window.getElectronRequestToken()}`
        };
    } else {
        return {
            header: __AUTH_HEADER,
            value: `${__AUTH_PREFIX} ${getToken()!.get('access_token')}`
        };
    }
};

/**
 * 刷新 access token
 */
export const refreshToken = (): Promise<any> => {
    return new Promise((resolve, reject) => {
        fetch(__REFRESH_URL, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `client_id=${__APP_ID}&code=${getToken()!.get('refresh_token')}`
        })
            .then((response) => {
                return response.json();
            }).then((ret) => {
                if (ret.result) {
                    resolve(ret.userData);
                } else {
                    reject(ret.userData);
                }
            }).catch((error) => {
                reject({
                    name: 'Refresh access token failed',
                    message: `刷新授权票据失败：${error.message}`,
                    code: 0
                });
            });
    });
};

export const loadToken = () => {
    const token = localStorage.getItem(DEFAULT_TOKEN_KEY);

    if (null === token || token.length === 0) {
        return null;
    } else {
        tokenCache = Immutable.fromJS(JSON.parse(token));
    }

    return tokenCache;
};
export const saveToken = (token: string) => {
    const savingToken = {
        ...JSON.parse(token),
        create_on: (new Date()).getTime()
    };
    localStorage.setItem(DEFAULT_TOKEN_KEY, JSON.stringify(savingToken));
    loadToken();
};
export const clearToken = () => {
    localStorage.removeItem(DEFAULT_TOKEN_KEY);
    tokenCache = undefined;
};

export const loadUser = () => {
    const user = localStorage.getItem(DEFAULT_USE_INFO_KEY);

    if (null === user || user.length === 0) {
        return null;
    } else {
        userCache = Immutable.fromJS(JSON.parse(user));
    }

    return userCache;
};
export const saveUser = (user: string) => {
    localStorage.setItem(DEFAULT_USE_INFO_KEY, user);
    loadUser();
};
export const clearUser = () => {
    localStorage.removeItem(DEFAULT_USE_INFO_KEY);
    userCache = undefined;
};
